<script setup lang="ts">
import { ref, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { usePropertyStore } from '@/stores/property'
import { storeToRefs } from 'pinia'
import type { ParkData } from '@/types'

const propertyStore = usePropertyStore()
const { allParks } = storeToRefs(propertyStore)

// 分页相关状态
const pageNum = ref(1)
const pageSize = ref(10)

const sortedParks = computed(() => {
  // 克隆数组以避免直接修改 store state，然后排序
  return [...allParks.value].sort((a, b) => a.name.localeCompare(b.name, 'zh-Hans-CN'));
});

// 分页后的数据
const paginatedParks = computed(() => {
  const start = (pageNum.value - 1) * pageSize.value;
  return sortedParks.value.slice(start, start + pageSize.value);
});

const dialogVisible = ref(false)
const isEdit = ref(false)

// 处理分页事件
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  pageNum.value = 1; // 重置到第一页
};

const handleCurrentChange = (newPage: number) => {
  pageNum.value = newPage;
};

const formRef = ref<FormInstance>()
const formModel = ref<Partial<ParkData>>({
  name: '',
  location: '',
  remarks: '',
  buildingCount: 0,
  managerName: '',
  contact: ''
})

const rules = ref<FormRules>({
  name: [{ required: true, message: '请输入园区名称', trigger: 'blur' }],
  managerName: [{ required: true, message: '请输入园区管理者', trigger: 'blur' }]
})

// 用于编辑时存储当前项ID
let currentParkId: string | null = null;

const openDialog = (park?: ParkData) => {
  dialogVisible.value = true
  isEdit.value = !!park

  nextTick(() => {
    formRef.value?.resetFields()
    if (park) {
      currentParkId = park.id
      formModel.value = { ...park }
    } else {
      currentParkId = null
      formModel.value = { name: '', location: '', remarks: '', buildingCount: 0, managerName: '', contact: '' }
    }
  })
}

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value && formModel.value.id) {
        // 使用类型断言来确保类型正确
        propertyStore.updatePark(formModel.value as ParkData)
        ElMessage.success('园区信息更新成功！')
      } else {
        propertyStore.addPark(formModel.value as Omit<ParkData, 'id'>)
        ElMessage.success('新园区添加成功！')
      }
      dialogVisible.value = false
    } else {
      ElMessage.error('请检查表单输入！')
    }
  })
}

const handleDelete = (park: ParkData) => {
  ElMessageBox.confirm(`您确定要删除【${park.name}】吗？这将是一个不可恢复的操作。`, '危险操作确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    propertyStore.deletePark(park.id)
    ElMessage.success(`园区【${park.name}】已成功删除。`)
  }).catch(() => {
    ElMessage.info('已取消删除操作。')
  });
}
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>园区管理</span>
        <el-button type="primary" @click="openDialog()">
          <el-icon><Plus /></el-icon>
          <span>添加园区</span>
        </el-button>
      </div>
    </template>

    <el-table :data="paginatedParks" style="width: 100%" border stripe>
      <el-table-column type="index" label="#" width="60" align="center" />
      <el-table-column prop="name" label="园区名称" align="center" sortable :sort-method="(a: ParkData, b: ParkData) => a.name.localeCompare(b.name, 'zh-Hans-CN')" />
      <el-table-column prop="location" label="园区位置" align="center" />
      <el-table-column prop="buildingCount" label="楼栋数量" align="center" />
      <el-table-column prop="managerName" label="园区管理者" align="center" />
      <el-table-column prop="contact" label="联系方式" align="center" />
      <el-table-column prop="remarks" label="备注" align="center" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="{ row }">
          <el-button text type="primary" @click="openDialog(row)">编辑</el-button>
          <el-button text type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="allParks.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>

  <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑园区信息' : '添加新园区'"
      width="500px"
      :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px" style="padding: 20px 0;">
      <el-form-item label="园区名称" prop="name">
        <el-input v-model="formModel.name" placeholder="请输入园区名称" />
      </el-form-item>
      <el-form-item label="楼栋数量" prop="buildingCount">
        <el-input-number v-model="formModel.buildingCount" :min="0" placeholder="请输入楼栋数量"/>
      </el-form-item>
      <el-form-item label="园区管理者" prop="managerName">
        <el-input v-model="formModel.managerName" placeholder="请输入园区管理者姓名" />
      </el-form-item>
      <el-form-item label="联系方式" prop="contact">
        <el-input v-model="formModel.contact" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="园区位置" prop="location">
        <el-input v-model="formModel.location" placeholder="请输入园区位置" />
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="formModel.remarks" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-button > span {
  margin-left: 8px;
}
</style>